package org.jfonia.util;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Maintains a logging list of objects deriving from a common type E.
 * Typically E equals Throwable or Exception. The
 * 
 * @author Wijnand
 */

public class Logger<E> { 
	
	private ArrayList<E> list = new ArrayList<E>();
	
	/**
	 * Clears the list.
	 */
	public void clear()
	{
		list.clear();
	}

	/**
	 * Adds an object to the exception list, and returns it.
	 * The returned object has the same type as the argument,
	 * allowing typed chaining.
	 * <p>
	 * If E is Throwable (or another Exception type), then the
	 * returned object can still be used in a throw statement.
	 * <p>
	 * e.g.
	 * <pre>
	 *     throw logger.log(new FooException("blabla");
	 * </pre>
	 * where logger is an instance of ExceptionLogger&lt;Throwable&gt; .
	 */
	public <T extends E> T log(T e) {
		list.add(e);
		return e;
	}
	
		
	/**
	 * @return the list of objects.
	 */
	public List<E> getList()
	{
		return list;
	}
	
	/**
	 * Writes all objects (toString()) to PrintWriter.
	 */
	public void report(PrintWriter out)
	{
		for (E e: list)
			out.println(e);
	}
	
	/**
	 * Writes all objects (toString()) to std-out
	 */
	public void report()
	{
		for (E e: list)
			System.out.println(e);
	}
}
